package trading.algo.BullTask;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import trading.algo.TimerKillerTask;
import trading.bo.DBAccessorBO;
import trading.bo.EmailAccessorBO;
import trading.bo.IBAccessorBO;
import trading.dataentry.MonitoredStocks;
import trading.dataentry.StockPositionOrOrder;
import trading.util.Constants;

public class UpdateTrailOrderMasterTask extends TimerTask {

	private IBAccessorBO ibAccessorBO;
	private DBAccessorBO dbAccessorBO;
	private EmailAccessorBO emailAccessorBO;
	private Double historicalLow;
	
	public UpdateTrailOrderMasterTask(IBAccessorBO ibAccessorBO,
			DBAccessorBO dbAccessorBO, EmailAccessorBO emailAccessorBO, Double historicalLow) {
		this.ibAccessorBO = ibAccessorBO;
		this.dbAccessorBO = dbAccessorBO;
		this.emailAccessorBO = emailAccessorBO;
		this.historicalLow = historicalLow;
	}
	
	@Override
	public void run() {
	    if (this.historicalLow == null) {
	        this.historicalLow = this.dbAccessorBO.getMonitoredStockData(MonitoredStocks.TICKERS.UVXY.name()).getHistoricalLow();
	    }
		List<StockPositionOrOrder> openTrailOrders = this.dbAccessorBO
				.getOpenTrailOrder();
		double trailAmount = historicalLow
				* Constants.Algo.BULL_SHORT_PROTECTION_PERCENTAGE / 100.0;
		Timer timer = new Timer();
		int taskID = 0;
		for (int i = 0; i < openTrailOrders.size(); i++, taskID += 2) {
			StockPositionOrOrder trailOrder = openTrailOrders.get(i);
			UpdateTrailAmountTask task = new UpdateTrailAmountTask(ibAccessorBO, emailAccessorBO, trailOrder, trailAmount, trailAmount + historicalLow);
			timer.schedule(task, taskID * 1000);
		}
		TimerKillerTask timerKillerTask = new TimerKillerTask(timer);
		timer.schedule(timerKillerTask, taskID * 1000);
	}

}
